package com.chenchao.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/16 17:10
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.javathread.Test4.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * Lock锁
 */
public class Test4 {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new TicketRunImp());
        Thread thread2 = new Thread(new TicketRunImp());
        Thread thread3 = new Thread(new TicketRunImp());

        thread1.start();
        thread2.start();
        thread3.start();
    }
}
class TicketRunImp implements Runnable {
    static Lock l=new ReentrantLock();
    //l是成员变量就是对象锁
    //是静态成员变量就是类锁
    public TicketRunImp() {
    }

    private static int ticketNum=1000;
    @Override
    public void run() {
        while (true){

            l.lock();
            try {
                if (ticketNum > 0) {
                    ticketNum--;
                    System.out.println("还剩票" + ticketNum + "张");
                } else {
                    System.out.println("票已经售完！");
                    System.exit(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                l.unlock();
                //防止中间语句出问题解不了锁，把解锁放在try/catch语句块中
            }
        }

    }

}